//
//  HomeViewController.m
//  QuickCure1
//
//  Created by maoge on 16/10/30.
//  Copyright © 2016年 maoge. All rights reserved.
//

#import "HomeViewController.h"
#import "Weather.h"
#import "HomeWeatherView.h"
#import "HomeChooseCityController.h"

#import "ProgressManager.h"
#import "ViewController.h"
#import <SDCycleScrollView.h>
#import <UIImageView+WebCache.h>

#import "HomeFlowLayout.h"
#import "HomeCollectionCell.h"
#import <AFNetworking.h>

#import "SicknessViewController.h"


#import "LBXScanView.h"
#import "LBXScanResult.h"
#import "LBXScanWrapper.h"
#import "SubLBXScanViewController.h"
#import <UMSocialCore/UMSocialCore.h>
#import <UMSocialUIManager.h>

@interface HomeViewController ()<UICollectionViewDelegate , UICollectionViewDataSource>

@property(nonatomic ,strong) Weather *weather;

@property(nonatomic ,weak) NSString *cityName;

@property(nonatomic ,strong) UIView *headerView;


@end


static NSString *cellID = @"COLLECTION_CELL";
static NSString *headerID = @"headerID";
@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    
//    [[[ViewController alloc]init]test4];
//    [[[ViewController alloc]init]test5];
//    [[[ViewController alloc]init]test6];
//    [[[ViewController alloc]init]test7];
//    [[[ViewController alloc]init]test8];
//    [[[ViewController alloc]init]test9];
//    [[[ViewController alloc]init]test10];

    
    [self setupUI];
    
    //实时监听网络状态
    [self AFNReachability];
    
    //监听用户截屏分享
    [self didTaskScreenshot];
    
}

#pragma mark : - 监听用户截屏分享
-(void)didTaskScreenshot{
    
    [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationUserDidTakeScreenshotNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        //        [ProgressManager alertInfoStatus:@"是否要分享"];
        
        __weak typeof(self) weakSelf = self;
        [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMShareMenuSelectionView *shareSelectionView, UMSocialPlatformType platformType) {
            
            [weakSelf shareTaskScreenShot:platformType];
        }];
        
    }];
    
}

//分享截屏照片
-(void)shareTaskScreenShot:(UMSocialPlatformType)platformType{
    
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    UMShareImageObject *shareObject = [[UMShareImageObject alloc]init];
    
    
    [shareObject setShareImage:[self imageWithScreenshot]];
    
    messageObject.shareObject = shareObject;
    
    //调用分享借口
    [[UMSocialManager defaultManager]shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id result, NSError *error) {
        
        //弹框
        NSString *alert = nil;
        if (!error) {
            alert = [NSString stringWithFormat:@"恭喜恭喜，图片分享完成"];
            
        }
        else{
            
            alert = [NSString stringWithFormat:@"分享失败，此功能正在开通中...code:%d\n",(int)error.code];
        }
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"大神班" message:alert delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alertView show];
    }];
    
}

-(UIImage *)imageWithScreenshot{
    
    CGSize imageSize = CGSizeZero;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    
    if (UIInterfaceOrientationIsPortrait(orientation)) {
        
        imageSize = [UIScreen mainScreen].bounds.size;
    }else{
        
        imageSize = CGSizeMake(SCREEN_HEIGHT, SCREEN_WIDTH);
        
    }
    
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow *window in [UIApplication sharedApplication].windows) {
        
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, window.center.x, window.center.y);
        CGContextConcatCTM(context, window.transform);
        CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
        
        if (orientation == UIInterfaceOrientationLandscapeLeft) {
            
            CGContextRotateCTM(context, M_PI_2);
            CGContextTranslateCTM(context, 0, -imageSize.width);
        }else if (orientation == UIInterfaceOrientationLandscapeRight){
            
            CGContextRotateCTM(context, M_PI);
            CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
            
        }
        
        if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
            
            [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
        }else{
            
            [window.layer renderInContext:context];
            
        }
        
        CGContextRestoreGState(context);
        
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return [UIImage imageWithData:UIImagePNGRepresentation(image)];
    
}


- (void)setupUI {
        
    self.title = @"黑马快医";
    
    _cityName = @"上海";

    self.navigationController.navigationBar.barTintColor = kThemeColor;
    
    [self setupWeatherView:@"上海"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeCity:) name:kIsUserChooseCityNotificationKey object:nil];
    
    //设置轮播器
    [self setupCycleView];
    
    //设置分类模块
    [self setupSicknessPiece];
    
    //设置扫一扫
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"home_scan"] style:UIBarButtonItemStylePlain target:self action:@selector(saoYIsao)];
    
    self.navigationItem.rightBarButtonItem = item;
}

#pragma nark : - 设置扫一扫
-(void)saoYIsao{

    if (![self cameraPemission])
    {
        [self showError:@"没有摄像机权限"];
        return;
    }
    
    [self qqStyle];

}
- (BOOL)cameraPemission
{
    
    BOOL isHavePemission = NO;
    if ([AVCaptureDevice respondsToSelector:@selector(authorizationStatusForMediaType:)])
    {
        AVAuthorizationStatus permission =
        [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        
        switch (permission) {
            case AVAuthorizationStatusAuthorized:
                isHavePemission = YES;
                break;
            case AVAuthorizationStatusDenied:
            case AVAuthorizationStatusRestricted:
                break;
            case AVAuthorizationStatusNotDetermined:
                isHavePemission = YES;
                break;
        }
    }
    
    return isHavePemission;
}


#pragma mark -模仿qq界面
- (void)qqStyle
{
    //设置扫码区域参数设置
    
    //创建参数对象
    LBXScanViewStyle *style = [[LBXScanViewStyle alloc]init];
    
    //矩形区域中心上移，默认中心点为屏幕中心点
    style.centerUpOffset = 44;
    
    //扫码框周围4个角的类型,设置为外挂式
    style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle_Outer;
    
    //扫码框周围4个角绘制的线条宽度
    style.photoframeLineW = 6;
    
    //扫码框周围4个角的宽度
    style.photoframeAngleW = 24;
    
    //扫码框周围4个角的高度
    style.photoframeAngleH = 24;
    
    //扫码框内 动画类型 --线条上下移动
    style.anmiationStyle = LBXScanViewAnimationStyle_LineMove;
    
    //线条上下移动图片
    style.animationImage = [UIImage imageNamed:@"qrcode_scan_light_green"];
    
    //SubLBXScanViewController继承自LBXScanViewController
    //添加一些扫码或相册结果处理
    SubLBXScanViewController *vc = [SubLBXScanViewController new];
    vc.style = style;
    
    vc.isQQSimulator = YES;
    vc.isVideoZoom = YES;
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)showError:(NSString*)str
{
    [LBXAlertAction showAlertWithTitle:@"提示" msg:str chooseBlock:nil buttonsStatement:@"知道了",nil];
}





#pragma mark : - 设置分类模块
//设置分类模块
-(void)setupSicknessPiece{

    CGFloat y = 64 + (110 + 200)/667.0 * SCREEN_HEIGHT ;
    
    UICollectionView *collectionV = [[UICollectionView alloc]initWithFrame:CGRectMake(0, y, SCREEN_WIDTH, SCREEN_HEIGHT - y) collectionViewLayout:[[HomeFlowLayout alloc]init]];
    
    [self.view addSubview:collectionV];

    collectionV.delegate = self;
    collectionV.dataSource = self;
    
    [collectionV registerNib:[UINib nibWithNibName:@"HomeCollectionCell" bundle:nil] forCellWithReuseIdentifier:cellID];
    
    [collectionV registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerID];

}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return 6;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    HomeCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    
    [cell setImgForCollectionCellWithIndexpath:indexPath];
    
    return cell;

}

//设置组头
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{

    if (kind == UICollectionElementKindSectionHeader) {
        
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerID forIndexPath:indexPath];
        header.backgroundColor = [UIColor whiteColor];
        
        [self setHeaderView];
        
        [header addSubview:_headerView];
        
        return header;
    }
    
    return nil;
}

-(void)setHeaderView{

    UIButton *btn = [UIButton buttonWithType:0];
    [btn setImage:[UIImage imageNamed:@"xianhua"] forState:UIControlStateNormal];
    
    [btn setTitle:@"庸医通" forState:UIControlStateNormal];
    
    [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    
//    [btn sizeToFit];
    btn.frame = CGRectMake(0, 0, 100, 30);
    
    
    self.headerView = btn;

}

//collectionView点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    //沙盒判断当前是否登陆
    if ([self configureLoginView]) {
        if (indexPath.row==5)
        {
            UIWebView*webView=[[UIWebView alloc]initWithFrame:self.view.bounds];
            NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://202.106.210.115:18080/hyde-pluto-h360/nt/appEntrance.htm"]];
            
            [webView loadRequest:request];
            
            UIViewController*vc=[[UIViewController alloc]init];
            vc.view=webView;
            [self.navigationController pushViewController:vc animated:YES];
            
        }
        else
        {
            SicknessViewController *vc = [[UIStoryboard storyboardWithName:@"SicknessView" bundle:nil] instantiateInitialViewController];
            vc.ci1_id=indexPath.row+1;
            [self.navigationController pushViewController:vc animated:YES];
            
        }

    }
}





-(BOOL)configureLoginView{
    
    BOOL isLogin = [MLDefaults boolForKey:kIsUserLoginKey];
    
    if (!isLogin) {
        
        [ProgressManager alertInfoStatus:@"还没有登录哦"];
        return NO;
    }
    else
    {
        return YES;

    }
    
}

#pragma mark : -设置轮播器
   //设置轮播器
-(void)setupCycleView{

    //轮播器图片地址
    NSArray *imagesArray = @[
                             @"http://img.guahao.com/portal_upload/rollingnews/1453447883150.jpg",
                             @"http://img.guahao.com/portal_upload/mediafocus/1461826474435.jpg",
                             @"http://img.guahao.com/portal_upload/rollingnews/1461574027543.jpg"
                             ];
    
    
    SDCycleScrollView *cycleView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 110/667.0 * SCREEN_HEIGHT+64, SCREEN_WIDTH, 200/667.0 * SCREEN_HEIGHT) imageURLStringsGroup:imagesArray];
    
    cycleView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
    
    [self.view addSubview:cycleView];

}


//接受通知处理
-(void)changeCity:(NSNotification *)notification{

    NSString *str = notification.object;
    
    _cityName = str;
    
    [self setupWeatherWithCity:str];

}


/**
 结束移除通知
 */
-(void)dealloc{

    [[NSNotificationCenter defaultCenter]removeObserver:self];

    [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
}

-(void)setupWeatherWithCity:(NSString *)city{

    [[NetWorkManager sharedManager] loadWeatherWithCurrentCity:city successBlock:^(NSDictionary *cityDic) {
        
        NSLog(@"%@",cityDic);
        _weather = [Weather weatherWithDic:cityDic];
        
        [self setupWeatherView:city];
        
        
        
    } errorBlock:^(NSString *error) {
        
        [ProgressManager alertErrorStatus:error];
    }];

}

-(void)setupWeatherView:(NSString *)cityName{

    HomeWeatherView *weatherView = [HomeWeatherView homeWeatherView];
    
    weatherView.model = self.weather;
    
    [weatherView.cityBtn addTarget:self action:@selector(chooseCity) forControlEvents:UIControlEventTouchUpInside];
    
    //按钮下划线
    [weatherView.cityBtn setAttributedTitle:[[NSAttributedString alloc]initWithString:cityName attributes:@{NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)}] forState:UIControlStateNormal];
    
    [weatherView.cityBtn setTitle:cityName forState:UIControlStateNormal];
    
    [self.view addSubview:weatherView];
    
    [weatherView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.leading.trailing.equalTo(self.view);
        make.top.equalTo(self.mas_topLayoutGuide);
        make.height.offset(110/667.0 * SCREEN_HEIGHT);
        
    }];

}

-(void)chooseCity{

    HomeChooseCityController *cityVc = [[HomeChooseCityController alloc]init];
    
    [self.navigationController pushViewController:cityVc animated:YES];
    
}


#pragma mark : -  使用AFN框架检测网络状态
-(void)AFNReachability{

    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有网络");
                
                [ProgressManager alertInfoStatus:@"没有连接网络"];
                
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                NSLog(@"WiFi");
                static dispatch_once_t onceToken;
                dispatch_once(&onceToken, ^{
                    [self setupWeatherWithCity:_cityName];
                });
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                NSLog(@"有网络");
                static dispatch_once_t onceToken;
                dispatch_once(&onceToken, ^{
                    [self setupWeatherWithCity:_cityName];
                });
                break;
            }
            default:
                break;
        }
        
    }];
    
    [manager startMonitoring];

}

@end
